package com.xiia.admin.servlet;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.xiia.common.servlet.FrameworkServlet;
import com.xiia.servcie.imp.AdService;
import com.xiia.service.inter.IAd;
import com.xiia.util.CheckConstant;
import com.xiia.util.CommonConstant;
import com.xiia.util.ParamUtil;
import com.xiia.util.StringUtil;
import com.xiia.vo.Ad;
import com.xiia.vo.User;
import com.xiia.util.Pager;

/**
 * 
 * @author 张文龙 2014-11-4 9:46
 *
 */
@WebServlet("/ad.do")
public class AdServlet extends FrameworkServlet {
	private static final long serialVersionUID = 1L;
	private String ret = null;
	private IAd iAdService = new AdService();
	private Pager page = null;

	/**
	 * 查询数据库可以公布的广告
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String showPublish(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Ad advert = new Ad();
		advert.setStatus(CheckConstant.STATUS_CHECK_PASS);
		List<Ad> ad = iAdService.selectAd(advert);
		request.setAttribute("advert", ad);
		if (ad != null) {
			// System.out.println("快到碗里来");
			return "bclient/ad/publishAd.jsp";
		}
		// 失败返回页面待定
		return "index.jsp";
	}

	/**
	 * 点击公布按钮后执行此方法改变status
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String publish(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// System.out.println("快到这里来");
		Ad advert = new Ad();
		String[] id = request.getParameterValues("publish");
		Date date = new Date();
		for (int i = 0; i < id.length; i++) {
			advert.setStatus(CheckConstant.STATUS_PUBLISH_DONE);
			advert.setAdId(StringUtil.stringToInt(id[i]));
			iAdService.releaseAd(advert);
		}
		return showPublish(request, response);
	}

	/**
	 * 接收页面数据录入数据库
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws FileUploadException 
	 * @throws UnsupportedEncodingException 
	 * @throws Exception 
	 */
	public String entry(HttpServletRequest request, HttpServletResponse response) throws FileUploadException, UnsupportedEncodingException
			{

		Ad ad = new Ad();
		User loginUser = (User) request.getSession().getAttribute(
				ParamUtil.LOGIN_USER);
		resString = "";
		// 得到一个上传的对象upload
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		List<FileItem> items;
		FileItem upItem = null;
		items = upload.parseRequest(request);
		for (FileItem item : items) {
			System.out.println(item.toString());
			if (item.isFormField()) {
				// 普通的表单属性，封装到ad中
				String fieldName = item.getFieldName();
				System.out.println("name:"+fieldName);
				if (fieldName.equals("adName")){
					String adName = new String(item.getString().getBytes("ISO-8859-1"),"UTF-8");
					ad.setAdName(adName);
				}else if (fieldName.equals("adType")) {
					int adType = Integer.parseInt(item.getString().trim());
					ad.setAdType(adType);
				}else if (fieldName.equals("content")) {
					String content = new String(item.getString().getBytes("ISO-8859-1"),"UTF-8");
					ad.setContent(content);
				}else if (fieldName.equals("adPath")) {
					ad.setAdPath(item.getString());
				}
				
			} else {
				// 要广告文件
				upItem = item;
				// 1.控制大小
				if (item.getSize() > ParamUtil.AD_FILE_SIZE * 1024 * 1024) {
					resString = "对不起，您的广告文件超出" + ParamUtil.AD_FILE_SIZE + "M";
				}
			}
		}
		if (resString.length() > 0) {
			// 不符合要求的广告
			request.setAttribute("resString", resString);
			return "bclient/ad/entryAd.jsp";
		}
		// 上传文件到服务器
		if (upItem != null) {
			// server://upload/userId/ad/2014-11-17/uuid.xxx
			String root = request.getSession().getServletContext()
					.getRealPath("/");// D:\Tomcat 7.0\wtpwebapps\XIIA\
			// 上传到upload/userId/resource/2014-7-25/file.jpg
			String currentDate = StringUtil.getCurrentDateInDir();
			String extention = StringUtil.getFileExtention(upItem.getName());
			String uploadDir = "upload/" + loginUser.getUserId() + "/ad/"
					+ currentDate + "/";
			String relativePath = uploadDir + UUID.randomUUID() + extention;

			try {
				uploadFileByItem(upItem, relativePath, uploadDir, root);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ad.setDbPath(relativePath);
		}
		ad.setStatus(CheckConstant.STATUS_WRITE_DONE);
		ad.setCreateTime(new Date());
		ad.setUser(loginUser);
		//将ad写入到数据库中
		if (iAdService.entryAd(ad)) {
			resString = "录入成功！";
			request.setAttribute("resString", resString);
			return "bclient/ad/entryAd.jsp";
		} else {
			resString = "录入失败！";
			request.setAttribute("resString", resString);
			return "bclient/ad/entryAd.jsp";
		}

	}

	/**
	 * 将要审核的广告改变状态并添加到审核表
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String check(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Ad advert = new Ad();
		String id = request.getParameter("adId");
		User user = (User) request.getSession().getAttribute(
				ParamUtil.LOGIN_USER);

		if (id == null) {
			ret = "你未选择广告";
			request.setAttribute("ret", ret);
			return showUpdate(request, response);
		}
		advert.setStatus(CheckConstant.STATUS_WAIT_CHECK);
		advert.setAdId(StringUtil.stringToInt(id));
		iAdService.checkAd(advert);
		iAdService.addAd(advert);
		advert.setUserId(user.getUserId());
		ret = "发送成功！";
		request.setAttribute("ret", ret);
		return showUpdate(request, response);
	}

	/**
	 * 查询要修改的广告（修改是在广告在状态为：编辑完成（字段1），审核不通过（字段4），撤除广告（字段6））
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String showUpdate(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int currentPage = 1;
		if (request.getParameter("currentPage") != null) {
			currentPage = StringUtil.stringToInt(request
					.getParameter("currentPage"));
		}
		page = new Pager();
		int totalCount = iAdService.getAdNum();
		page.paging(currentPage, 10, totalCount);
		page = iAdService.selectAd1(page);
		request.setAttribute("page", page);
		return "bclient/ad/updateAd.jsp";
	}

	/**
	 * 跳转到修改界面
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String update(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String adId = request.getParameter("adId");
		Ad advert = new Ad();
		advert.setAdId(StringUtil.stringToInt(adId));
		List<Ad> adv = iAdService.selectAd(advert);
		request.setAttribute("adv", adv);
		if (iAdService.selectAd(advert) != null) {
			return "bclient/ad/update.jsp";
		}
		return "index.jsp";
	}

	/**
	 * 修改广告链接
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String updateLink(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		{
			Date date = new Date();
			String path = request.getParameter("adPath");
			String id = request.getParameter("adId");
			System.out.println(id);
			Ad advert = new Ad();
			advert.setLastUpdateTime(date);
			advert.setAdId(StringUtil.stringToInt(id));
			advert.setAdPath(path);
			// System.out.println(id);
			if (iAdService.updateAdLink(advert)) {
				ret = "修改成功";
			} else {
				ret = "修改失败";
			}
		}
		request.setAttribute("ret", ret);
		return showUpdate(request, response);
	}

	/**
	 * 点击撤除广告执行此方法从数据库中取得数据
	 * 
	 * @param request
	 * @param reponse
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String showUndo(HttpServletRequest request,
			HttpServletResponse reponse) throws ServletException, IOException {
		Ad advert = new Ad();
		advert.setStatus(CheckConstant.STATUS_PUBLISH_DONE);
		List<Ad> ad3 = iAdService.selectAd(advert);
		request.setAttribute("ad3", ad3);
		if (ad3 != null) {
			return "bclient/ad/undoAd.jsp";
		}
		return "index.jsp";
	}

	/**
	 * 点击撤除广告执行此方法
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String undo(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String[] id = request.getParameterValues("undo");
		Ad advert = new Ad();
		for (int i = 0; i < id.length; i++) {
			advert.setStatus(CheckConstant.STATUS_CHECK_PASS);
			advert.setAdId(StringUtil.stringToInt(id[i]));
			iAdService.undoAd(advert);
		}
		return showUndo(request, response);
	}

	/**
	 * 点击删除按钮执行此方法
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String delete(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("adId");
		Ad advert = new Ad();
		advert.setAdId(StringUtil.stringToInt(id));
		iAdService.deleteAd(advert);
		ret = "删除成功";
		request.setAttribute("ret", ret);
		return showUpdate(request, response);
	}
	/**
	 * 通过fileupload写文件到服务器上
	 * @param item
	 * @param relativePath upload/userId/resource/2014-7-25/uuid.jpg
	 * @param uploadDir upload/userId/resource/2014-7-25/file.jpg
	 * @param root D:/Tomcat 7.0/wtpwebapps/xiia/upload/userId/resource/2014-7-25/uuid.jpg
	 * @throws Exception
	 */
	private void uploadFileByItem(FileItem item,String relativePath,String uploadDir,String root) 
			throws Exception{
		String serverDirPath = root + uploadDir;
		File dir = new File(serverDirPath);
		if(!(dir.isDirectory() && dir.exists())){
			dir.mkdirs();
		}
		File file = new File(root+relativePath);
		item.write(file);
	}
	/**
	 * 封装表单
	 * 
	 * @param r
	 * @param response
	 * @return
	 */
	private Ad adForm(HttpServletRequest r, HttpServletResponse response) {
		Ad advert = new Ad();
		System.out.println("name" + r.getParameter("adName"));
		if (r.getParameter("adName") != null) {
			advert.setAdName(r.getParameter("adName"));
		}
		System.out.println("type" + r.getParameter("adType"));
		if (r.getParameter("adType") != null) {
			advert.setAdType(StringUtil.stringToInt(r.getParameter("adType")));
		}
		System.out.println("path" + r.getParameter("adPath"));
		if (r.getParameter("adPath") != null) {
			advert.setAdPath(r.getParameter("adPath"));
		}
		System.out.println("content" + r.getParameter("content"));
		if (r.getParameter("content") != null) {
			advert.setContent(r.getParameter("content"));
		}
		return advert;
	}

}
